<?php

namespace Xrfg\Api\Trading\Spot\Listeners;

use Exception;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Xrfg\Api\Trading\Spot\Events\OrderCreatedEvent;
use Xrfg\Core\Trading\Spot\Models\Order;

class TakerRobot
{
    public function handle(OrderCreatedEvent $event)
    {
        $userId = 100001;
        $apiKey = 'E0Ru3mRQs8GcRhBLOykOt1lKbstDQJmaa0jQke9lXGNckbljUqTSpIPgHXG5Xa1z';
        $apiSecret = '8aDdX2y5bJ362dZoqYqfPFZUd7ESqTMsgEJHm3L6yrdUYKfxeXGTBMmQzazus5zn';

        /** @var Order $order */
        $order = $event->order;

        if (!$order->exists) {
            return;
        }

        // 不处理自己挂单
        if ($order->user_id === $userId) {
            return;
        }

        // 市价单不处理
        if (Order::TYPE_MARKET === $order->type) {
            return;
        }

        // 不在列表中的交易对不处理
        if (!in_array($order->symbol, ['BTC/USDT', 'ETH/USDT', 'EOS/USDT', 'XRP/USDT', 'TRX/USDT'])) {
            return;
        }

        // 判断价格
        $redis = Redis::connection();
        $symbol = strtolower(str_replace('/', '', $order->symbol));
        if (Order::SIDE_BUY === $order->side) {
            $result = $redis->zrange('huobi:depth:'.$symbol.':asks', 0, -1, ['WITHSCORES' => true]);
            if (!$result) {
                return;
            }
            ksort($result);
            $price = array_key_first($result);
            if ($price > $order->price) {
                return;
            }
        } else {
            $result = $redis->zrange('huobi:depth:'.$symbol.':bids', 0, -1, ['WITHSCORES' => true]);
            if (!$result) {
                return;
            }
            krsort($result);
            $price = array_key_first($result);
            if ($price < $order->price) {
                return;
            }
        }

        // 创建订单
        $http = new Client();
        $body = [
            'symbol' => $order->symbol,
            'side' => Order::SIDE_BUY === $order->side ? Order::SIDE_SELL : Order::SIDE_BUY,
            'order_type' => Order::TYPE_LIMIT,
            'price' => $order->price,
            'number' => $order->number,
            'timestamp' => time(),
            'timeoffset' => 5,
        ];
        ksort($body);

        $payloads = '';
        foreach ($body as $key => $value) {
            $payloads .= "$key=$value";
            if (array_key_last($body) !== $key) {
                $payloads .= '&';
            }
        }

        $algo = config('api_key.algo');
        $signature = hash_hmac($algo, $payloads, $apiSecret);
        $body['signature'] = $signature;

        try {
            $response = $http->post('http://127.0.0.1/v1/orders', [
                'headers' => ['X-API-KEY' => $apiKey],
                'form_params' => $body,
            ]);
            Log::info($response->getBody()->getContents());
        } catch (Exception $exception) {
            Log::error($exception->getMessage());
        }
    }
}
